package com.seasugar.raggie.controller;

import com.seasugar.raggie.common.R;
import com.seasugar.raggie.utils.QiniuUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("common")
public class CommonController {

    //获取yml中的属性
//    @Value("${reggie.img}")
//    private String basePath;
    @Autowired
    private QiniuUtil qiniuUtil;

    @PostMapping("upload")
    //注意：MultipartFile的名字不能随便起，应和前端的文件name保持一致
    //file是个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会被自动删除
    public R upload(MultipartFile file) {
        //夏目1.jpg
        log.info("文件名：{}", file.getOriginalFilename());
        //file
        log.info("文件名：{}", file.getName());


        //将临时文件转存为永久性文件
        //判断默认目录是否存在
//            File dir=new File(basePath);
        //如果不存在就创建
//            if(!dir.exists())
//                dir.mkdir();
        String filename = file.getOriginalFilename();
        //解决覆盖问题
        String suffix = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID().toString() + suffix;
//            file.transferTo(new File(basePath+filename));
        boolean upload = qiniuUtil.upload(file, filename);
        if (upload)
            return R.success(filename);
        else
            return R.error("上传失败");
    }


    //下载文件
//    @GetMapping("download")
//    public void download(String name, HttpServletResponse response) {
//        log.info("下载文件{}", name);
//        try {
////            //输入流读文件
////            FileInputStream is = new FileInputStream("rbjvd01tv.bkt.clouddn.com" + name);
////
////            //输出流写文件
////            ServletOutputStream os = response.getOutputStream();
////            response.setContentType("image/jpg");
////            int len = 0;
////            byte[] bytes = new byte[1024];
////            while ((len = is.read(bytes)) != -1) {
////                os.write(bytes, 0, len);
////                os.flush();
////            }
//            qiniuUtil.download(name);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
